/**
 * 自定义协议，用于通过链接唤起程序
 */
const { app, BrowserWindow, ipcMain } = require('electron')

module.exports = () => {
  let searchParams = {}
  let customProtocol1 = 'xue5hen'
  let customProtocol2 = 'xue5hen2'
  let customProtocolHandler = (eventType, argv) => {
    searchParams = {}
    let urlStr = ''
    if (!argv) return
    if (process.platform === 'win32' && eventType === 'second-instance') {
      // 检查参数末尾是否有多余的斜杠，若有则去除
      // while (/\/$/.test(urlStr)) {
      //   urlStr = urlStr.slice(0, urlStr.length - 1)
      // }
      urlStr = urlStr.replace(/\/+$/g, '')
      // 方案1
      // Object.keys(argv).forEach(k => {
      //   if (new RegExp(`^(${customProtocol1}|${customProtocol2})://`, 'i').test(argv[k] || '')) {
      //     urlStr = argv[k]
      //   }
      // })

      // 方案2
      let offset = app.isPackaged ? 1 : 2
      urlStr = argv.find((arg, i) => i >= offset && new RegExp(`^(${customProtocol1}|${customProtocol2}):`, 'i').test(arg))
    } else if (process.platform === 'darwin' && eventType === 'open-url') {
      urlStr = argv || ''
    }
    if (urlStr) {
      // 方案1
      // let urlObj = new URL(urlStr)
      // searchParams = JSON.parse(JSON.stringify(urlObj.searchParams))

      // 方案2
      let str = urlStr.match(new RegExp(`^(${customProtocol1}|${customProtocol2})://(.*\\?)?(.+)`, 'i'))[3] || ''
      let arr = str.split('&')
      arr.forEach(v => {
        let _arr = v.split('=')
        searchParams[_arr[0]] = _arr[1] || ''
      })
      // 将url信息发送给网页
      let myWindows = BrowserWindow.getAllWindows()
      myWindows.forEach(win => {
        if (win && !win.isDestroyed()) {
          win.webContents.send('custom-protocol', searchParams)
        }
      })
    }
  }
  app.setAsDefaultProtocolClient(customProtocol1)
  app.setAsDefaultProtocolClient(customProtocol2)
  if (process.argv.length > 1) {
    if (!app.isReady()) {
      app.once('browser-window-created', () => {
        app.emit('second-instance', null, process.argv)
        // setTimeout(() => {
        //   customProtocolHandler('second-instance', process.argv)
        // }, 2000)
      })
    } else {
      app.emit('second-instance', null, process.argv)
      // setTimeout(() => {
      //   customProtocolHandler('second-instance', process.argv)
      // }, 2000)
    }
  }
  app.on('second-instance', (event, argv) => {
    if (process.platform === 'win32') {
      customProtocolHandler('second-instance', argv)
    }
  })
  app.on('open-url', (event, urlStr) => {
    customProtocolHandler('open-url', urlStr)
  })
  ipcMain.on('get-custom-protocol-params', (event) => {
    if (Object.keys(searchParams).length > 0) {
      event.sender.send('custom-protocol', searchParams)
    }
  })
}
